//
//  File.swift
//  zpzk_shop
//
//  Created by Qingke on 16/5/21.
//  Copyright © 2016年 Qingke. All rights reserved.
//

import Foundation
import UIKit

extension UIImageView {
    func othersetImage(url: String,placeHold: UIImage) {
        
        let NSUrl = NSURL(string: url)
        let pathName = NSUrl!.lastPathComponent //返回链接的最后一段，默认为pathName
        let path  = UilityFile.filePath(pathName!)
        if let img = UilityFile.readFromFile(path) {
            self.image = img
        }else {
            let request = NSURLRequest(URL: NSUrl!)
            NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(), completionHandler: { response, data, error in
                if (error == nil){
                    //异步请求得到的数据  这一过程没有错误
                    dispatch_sync(dispatch_get_main_queue(), { 
                        if let image = UIImage(data: data!) {
                            self.image = image
                            //再把得到的data写入到文件中
                            let IsSuccess = UilityFile.writeToFile(path, image: data!)
                            if !IsSuccess {
                                print("errror path : \(path)")
                            }
                        } else {
                            //得到的data转化image是空的
                            self.image = placeHold
                            return
                        }
                    })
                } else {
                    //异步请求  不能得到数据，将占位图片赋值给UIimageview的image
                    self.image = placeHold
                    
                }
            })
            
        }
    }
}